package com.cardone.common.web.support;

import java.io.IOException;
import java.nio.charset.Charset;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.cardone.common.util.MapperUtils;

/**
 * @author yaohaitao
 *
 */
@Slf4j
public class CardOneHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
	@Setter
	@Getter
	private Charset charset = Charsets.UTF_8;

	public CardOneHttpMessageConverter() {
		super(new MediaType(com.google.common.net.MediaType.ANY_APPLICATION_TYPE.type(), com.google.common.net.MediaType.ANY_APPLICATION_TYPE.subtype(), Charsets.UTF_8), new MediaType(com.google.common.net.MediaType.ANY_APPLICATION_TYPE.type(), "*+json", Charsets.UTF_8));
	}

	@Override
	protected Object readInternal(final Class<? extends Object> clazz, final HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
		String jsonString = null;

		try {
			jsonString = IOUtils.toString(inputMessage.getBody(), this.charset);
		} catch (final Exception e) {
			CardOneHttpMessageConverter.log.error(e.getMessage(), e);
		}

		if (StringUtils.isBlank(jsonString)) {
			return null;
		}

		CardOneHttpMessageConverter.log.debug(jsonString);

		if (String.class.equals(clazz)) {
			return jsonString;
		}

		return MapperUtils.getBeanForJson(clazz, jsonString);
	}

	@Override
	protected boolean supports(final Class<?> clazz) {
		return true;
	}

	@Override
	protected void writeInternal(final Object obj, final HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
		final String jsonString = MapperUtils.toJson(obj);

		CardOneHttpMessageConverter.log.debug(jsonString);

		final byte[] bytes = jsonString.getBytes(this.charset);

		outputMessage.getBody().write(bytes);
	}
}
